//
//  TapScrollViewViewController.m
//  IntimateGift
//
//  Created by zh on 14/12/20.
//  Copyright (c) 2014年 蔡宏业. All rights reserved.
//

#import "TapScrollViewViewController.h"
#import "ChoicenessCell.h"
#import "Choiceness.h"
#import "NetHandler.h"
#import "DetailsViewController.h"
#import "UIScrollView+Extension.h"
#import "UIScrollView+MJRefresh.h"

#define CHOICENESS @"choicenessReuse"

@interface TapScrollViewViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UITableView *myTableView;

@property (nonatomic, retain) NSMutableArray *arr;

@property (nonatomic, assign) NSInteger num;

@property (nonatomic, assign) NSInteger sum;


@end

@implementation TapScrollViewViewController

// 内存
- (void)dealloc
{
    [_myTableView release];
    [_arr release];
    [_banner release];
    [super dealloc];
}
// 初始化
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.arr = [NSMutableArray array];
        self.num = 12;
        self.sum = 0;
    }
    return self;
}
#pragma mark 设置tableView
- (void)installMyTableView
{
    //    CGRect rect = self.view.bounds;
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - 64) style:UITableViewStylePlain];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.myTableView];
    // 注册cell
    [self.myTableView registerClass:[ChoicenessCell class] forCellReuseIdentifier:CHOICENESS];
    [_myTableView release];
}
#pragma mark 网络请求
- (void)handleData
{
    
    NSString *str = [NSString stringWithFormat:@"http://api.liwushuo.com/v1/collections/%@/posts?limit=12&offset=0", [self.banner.target_id description]];
    NSLog(@"%@", str);
    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
        
        NSError *error = nil;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        NSDictionary *dic1 = [result objectForKey:@"data"];
        NSArray *arr = [dic1 objectForKey:@"posts"];
        for (NSDictionary *dic in arr) {
            Choiceness *choiceness = [[Choiceness alloc] initWithDictionary:dic];
            [self.arr addObject:choiceness];
        }
        [self.myTableView reloadData];
        [self setupRefresh];
    }];
}

- (void)setupRefresh
{
    //    NSLog(@"进入了setupRefresh");
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    
    [self.myTableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    //进入刷新状态(一进入程序就下拉刷新)
    [self.myTableView headerBeginRefreshing];
    
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.myTableView addFooterWithTarget:self action:@selector(footerRereshing)];
}



#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    
    //1. 在这调用请求网络数据方法（刷新数据）
    
    NSString *str = [NSString stringWithFormat:@"http://api.liwushuo.com/v1/collections/%@/posts?limit=12&offset=0", [self.banner.target_id description]];
    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
        
        NSError *error = nil;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        NSDictionary *dic1 = [result objectForKey:@"data"];
        NSArray *arr = [dic1 objectForKey:@"posts"];
        [self.arr removeAllObjects];
        for (NSDictionary *dic in arr) {
            Choiceness *choiceness = [[Choiceness alloc] initWithDictionary:dic];
            [self.arr addObject:choiceness];
        }
        [self.myTableView reloadData];
    }];
    
    
    //2. 2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.myTableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.myTableView headerEndRefreshing];
    });
}

//   进入加载状态
- (void)footerRereshing
{
    //1. 拼接口等操作
    // 请求加载数据
    NSString *str = [NSString stringWithFormat:@"http://api.liwushuo.com/v1/collections/%@/posts?limit=12&offset=%ld", [self.banner.target_id description], self.num];
    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
        NSError *error = nil;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        NSDictionary *dic1 = [result objectForKey:@"data"];
        NSArray *arr = [dic1 objectForKey:@"posts"];
        for (NSDictionary *dic in arr) {
            Choiceness *choiceness = [[Choiceness alloc] initWithDictionary:dic];
            [self.arr addObject:choiceness];
        }
        [self.myTableView reloadData];
        self.num = self.num + 12;
    }];
    
    
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.myTableView reloadData];
        [self.myTableView footerEndRefreshing];
    });
}


#pragma mark 点赞按钮
- (void)likeButtonClicked:(UIButton *)button
{
    NSInteger numberofCell = button.tag - 3000;
    Choiceness *choiceness = [self.arr objectAtIndex:numberofCell];
    if (self.sum % 2 == 0) {
        self.sum = self.sum + 1;
        NSString *likeCount = choiceness.likes_count;
        NSInteger like_count = [likeCount integerValue];
        like_count = like_count + 1;
        choiceness.likes_count = [NSString stringWithFormat:@"%ld", like_count];
        [self.myTableView reloadData];
    } else {
        
        self.sum += 1;
        NSString *likeCount = choiceness.likes_count;
        NSInteger like_count = [likeCount integerValue];
        like_count = like_count - 1;
        choiceness.likes_count = [NSString stringWithFormat:@"%ld", like_count];
        [self.myTableView reloadData];
        
    }
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.navigationController.navigationBar.alpha = 1;
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = [self.banner.target objectForKey:@"title"];
    self.view.backgroundColor = [UIColor whiteColor];
    [self installMyTableView];
    [self handleData];
    
    // Do any additional setup after loading the view.
}

#pragma  mark 设置cell
// cell个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arr.count;
}
// 重用
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 设置cell
    ChoicenessCell *cell = [tableView dequeueReusableCellWithIdentifier:CHOICENESS];
    Choiceness *chiceness = [self.arr objectAtIndex:indexPath.row];
    cell.choiceness = chiceness;
    [cell.likeButton addTarget:self action:@selector(likeButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    cell.likeButton.tag = 3000 + indexPath.row;
    return cell;
}

// cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.view.bounds.size.height / 3.0;
}
// 点击cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    // 传值 push
    DetailsViewController *detailsVC = [[DetailsViewController alloc] init];
    detailsVC.choiceness = [self.arr objectAtIndex:indexPath.row];
    [self.navigationController pushViewController:detailsVC animated:YES];
//    [detailsVC release];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
